#include "periodic_worker.h"

namespace afcore {
namespace log {

CPeriodicWorker::CPeriodicWorker(const std::function<void()> &callback, RSeconds interval) {
  active_ = (interval > RSeconds::zero());
  if (!active_) {
    return;
  }

  worker_thread_ = std::thread(
    [this, callback, interval]() {
      for (;;) {
        std::unique_lock<std::mutex> lock(this->mutex_);
        if (this->cv_.wait_for(lock, interval,
          [this]() {
            return !this->active_;
          })) {
          return; // active_ == false 退出线程
        }
        // 执行回调函数
        callback();
      }
    });
}
CPeriodicWorker::~CPeriodicWorker() {
  if (worker_thread_.joinable()) {
    {
      std::lock_guard<std::mutex> lock(mutex_);
      active_ = false;
    }
    cv_.notify_one();
    worker_thread_.join();
  }
}
} // !namespace log
} // !namespace afcore